/*
 * 1011. 二叉查找树中搜索区间
 * 
 * 描述
 * 给定两个值 k1 和 k2（k1 < k2）和一个二叉查找树的根节点。找到树中所有值在 k1 到 k2 范围内的节点。即打印所有x (k1 <= x <= k2) 其中 x 是二叉查找树的中的节点值。返回所有升序的节点值。
 * 
 * 样例
 * 如果有 k1 = 10 和 k2 = 22, 你的程序应该返回 [12, 20, 22].
 * 		20
 * 	   /  \
 *    8   22
 *   / \
 *  4   12
 * 
 * 2018.06.02 @jeyming
 * 
 * List排序：
 * https://blog.csdn.net/veryisjava/article/details/51675036
 * 
 * List常用操作
 * https://www.cnblogs.com/epeter/p/5648026.html
 * https://www.cnblogs.com/111testing/p/6602603.html
 * 
 * queue的使用方法
 * https://blog.csdn.net/together_cz/article/details/68927112
 * 
 * TreeSet用法：
 * https://www.cnblogs.com/ningvsban/archive/2013/05/06/3062535.html
 * 
 */
package search_range_in_binary_search_tree_1011;

import java.util.ArrayList;
import java.util.List;
import java.util.Queue;
import java.util.TreeSet;
import java.util.concurrent.ArrayBlockingQueue;

//Definition of TreeNode:
class TreeNode {
	public int val;
	public TreeNode left, right;
	public TreeNode(int val) {
		this.val = val;
		this.left = this.right = null;
	}
}

public class Search_range_in_binary_search_tree_1011 {

	/**
	 * @param root: param root: The root of the binary search tree
	 * @param k1: An integer
	 * @param k2: An integer
	 * @return: return: Return all keys that k1<=key<=k2 in ascending order
	 */
	public static List<Integer> searchRange(TreeNode root, int k1, int k2) {
		// write your code here
		TreeSet<Integer> treeSet = new TreeSet<Integer>();
		List<Integer> list=new ArrayList<Integer>();
		Queue<TreeNode> Q = new ArrayBlockingQueue<TreeNode>(1000);
		if(root!=null) {
			Q.add(root);
			treeSet.add(Q.peek().val);
			while(Q.peek()!=null) {
				boolean judgeL = false,judgeR = false;
				if(Q.peek().left != null) {
					treeSet.add(Q.peek().left.val);
					judgeL=true;
				}
				if(Q.peek().right != null) {
					treeSet.add(Q.peek().right.val);
					judgeR = true;
				}
				if(judgeL)
					Q.add(Q.peek().left);
				if(judgeR)
					Q.add(Q.peek().right);
				Q.remove();
			}
			java.util.Iterator<Integer> it = treeSet.iterator();
			while(it.hasNext()) {
				int tmp = it.next();
				if(tmp >= k1 && tmp <= k2) {
					list.add(tmp);
				}
			}
		}
		for(int i = 0; i < list.size(); ++i) {
			System.out.print(list.get(i) + " ");
		}
		return list;
	}

	public static void main(String[] args) {
		TreeNode tree = new TreeNode(2);
		tree.left=new TreeNode(1);
//		tree.right=new TreeNode(22);
//		tree.left.left=new TreeNode(4);
//		tree.left.right=new TreeNode(12);
		searchRange(tree,0,4);
		//searchRange({2,1},0,4);
		//{20,8,22,4,12} k1=10,k2=22
	}

}
